﻿using System.Xml;

namespace EFDemo
{
    public class XmlEntityHelper
    {
        public static List<XmlEntityComment> XmlToEntity()
        {
            var type = typeof(ProfessionalContingent);
            var aa=type.Name;

            string path = AppContext.BaseDirectory + "EFDemo.xml";
            XmlDocument doc = new XmlDocument();
            doc.Load(path);

            List<XmlEntityComment> list = new List<XmlEntityComment>();
            XmlNode? root = doc.SelectSingleNode("//members");
            foreach (XmlElement node in root)
            {
                string name = node.GetAttribute("name");
                string value = node.ChildNodes.Item(0).InnerText.Replace("\r\n", "").Trim();

                list.Add(new XmlEntityComment() { Name = name, Comment = value });
            }

            List<XmlEntityComment> result = new List<XmlEntityComment>();

            var tableList = list.Where(c => c.Name.Contains("T:")).ToList();
            foreach (XmlEntityComment node in tableList)
            {
                string[] tables = node.Name.Split(".");
                string tableName = tables[tables.Length - 1];

                XmlEntityComment one = new()
                {
                    Name = tableName,
                    Comment = node.Comment,
                    Column = new List<XmlEntityComment>()
                };

                string aaa = node.Name.Replace("T:", "P:");
                var columnList = list.Where(c => c.Name.Contains(aaa)).ToList();

                foreach (XmlEntityComment node2 in columnList)
                {
                    string[] columns = node2.Name.Split(".");
                    string columnName = columns[columns.Length - 1];

                    one.Column.Add(new XmlEntityComment() { Name = columnName, Comment = node2.Comment });
                }

                result.Add(one);
            }

            return result;
        }
    }

    public class XmlEntityComment
    {
        public string Name { get; set; }
        public string Comment { get; set; }

        public List<XmlEntityComment> Column { get; set; }
    }
}
